#coding:utf-8
from django.http import HttpResponse
import commands
from django.shortcuts import render
from .models import Person
from .forms import LoginForm
from .forms import RegisterForm
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login


def signin(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid(): 
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            #reluser = Person.objects.get(user=user).user
            #relpwd = Person.objects.get(user=user).password
            #return render(request, 'test.html',{'user':user,'password':password,'reluser':reluser})
            #if user==reluser and password == relpwd:
            user = authenticate(username=username, password=password)
             #messages.success(request,'登录成功')
            if user:
                login(request,user)
                return  HttpResponseRedirect("/")
             #   return render(request, 'index.html')
            else:
                #messages.success(request,'登录失败')
                ret = "登录失败，密码错误！"
                return render(request, 'test.html',{'ret':ret})
    else:
            form = LoginForm()
            return render(request, 'login.html', {'form':form})

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.set_password(form.cleaned_data['password'])
            new_user.save()

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request,user)
                return HttpResponseRedirect("/")

            #messages.success(request,'注册成功')
        else:
            return HttpResponse("对不起，注册未成功，请重新注册！")
    else:
        form = RegisterForm()
        return render(request, 'register.html', {'form':form})
